package cn.smile.controller;

import cn.smile.feign.Feign;
import cn.smile.pojo.User;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.sql.Timestamp;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: MaoSuyu
 * @User：John
 * @Date: 2019/5/18
 * @Time: 13:56
 * @Description: No Description
 */
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private EurekaClient eurekaClient;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private Feign feign;

    @GetMapping("/hello.do")
    public User hello(){
       /* //得到服务的info信息
        final InstanceInfo instanceInfo=eurekaClient.getNextServerFromEureka("producer",false);
        //得到服务的服务地址
        final String homePageUrl = instanceInfo.getHomePageUrl();
        System.out.println(homePageUrl);
        //实现producer的负载均衡
        final ServiceInstance producer = loadBalancerClient.choose("producer");
        System.out.println(producer.getHost()+"\t"+producer.getUri()+"\t"+producer.getServiceId());*/
        //使用了ribbon负载均衡以后可直接写服务名
        //User user=restTemplate.getForObject(producer.getUri()+"/hello/",User.class);
        System.out.println("毛苏雨："+Thread.currentThread().getName());
        return feign.getUser();
    }

    @GetMapping("/getUser.do")
    public User getUser(){
        System.out.println("刘思晴："+Thread.currentThread().getName());
        return feign.getUser(new User("刘思晴",new Timestamp(System.currentTimeMillis())));
    }


    @GetMapping("/test.do")
    public String test(){
        return feign.test();
    }

    @GetMapping("/hystrix.do")
    //该注解相当于配置了线程隔离，服务降级，熔断
    //@HystrixCommand(fallbackMethod = "hystrixFallBack")
    public String hystrix(){
        return feign.hystrix();
    }
    /**
     * 如果服务超时断路器将调用的方法
     * @return
     */
    public String hystrixFallBack(){
        return "服务器忙！";
    }

    @GetMapping("server.do")
    public String server(){
        return feign.getServer();
    }

    @GetMapping("service")
    public String service() throws Exception{
        Thread.sleep(8000);
        return "hello";
    }
}
